package org.zhaya.sdk.processors;

import com.google.common.collect.Maps;
import io.logz.sawmill.Doc;
import io.logz.sawmill.ProcessResult;
import io.logz.sawmill.Processor;
import io.logz.sawmill.annotations.ProcessorProvider;
import io.logz.sawmill.exceptions.ProcessorConfigurationException;
import io.logz.sawmill.exceptions.ProcessorExecutionException;
import io.logz.sawmill.utilities.JsonUtils;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.collections4.MapUtils;
import org.apache.commons.lang3.StringUtils;
import org.zhaya.sdk.util.ClonerUtils;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

@Slf4j
@ProcessorProvider(type = "transpose", factory = TransposeProcessor.Factory.class)
public class TransposeProcessor implements Processor {

    public static final String MULTI_DOC_FIELD = "_docs";

    private final List<String> fields;
    private final String targetNameField;
    private final String targetValueField;

    public TransposeProcessor(List<String> fields, String targetNameField, String targetValueField) {
        this.fields = fields;
        this.targetNameField = targetNameField;
        this.targetValueField = targetValueField;
    }

    @Override
    public ProcessResult process(Doc doc) {
        try {
            if (CollectionUtils.isNotEmpty(fields)) {
                Map<String, Object> docsMap = Maps.newHashMapWithExpectedSize(fields.size());
                for (String field : fields) {
                    if (doc.hasField(field)) {
                        docsMap.put(field, doc.getField(field));
                        doc.removeField(field);
                    }
                }

                if (MapUtils.isNotEmpty(docsMap)) {
                    List<Doc> docs = new ArrayList<>(docsMap.size());
                    for (Map.Entry<String, Object> entry : docsMap.entrySet()) {
                        Doc newDoc = ClonerUtils.deepClone(doc);
                        newDoc.addField(targetNameField, entry.getKey());
                        newDoc.addField(targetValueField, entry.getValue());
                        docs.add(newDoc);
                    }
                    doc.addField(MULTI_DOC_FIELD, docs);
                }
            }
        } catch (Exception e) {
            return ProcessResult.failure(String.format("failed to process doc to docs for fields %s", Arrays.toString(fields.toArray())),
                    new ProcessorExecutionException("docToDocs", e));
        }
        return ProcessResult.success();
    }

    public static class Factory implements Processor.Factory {

        @Override
        public TransposeProcessor create(Map<String, Object> config) {

            Configuration docToDocsConfig = JsonUtils.fromJsonMap(Configuration.class, config);

            List<String> fields = docToDocsConfig.getFields();
            if (CollectionUtils.isEmpty(fields)) {
                throw new ProcessorConfigurationException("failed to parse convert processor config, could not resolve fields");
            }

            String targetNameField = StringUtils.defaultIfBlank(docToDocsConfig.getTargetNameField(), "name");
            String targetValueField = StringUtils.defaultIfBlank(docToDocsConfig.getTargetValueField(), "value");
            return new TransposeProcessor(fields, targetNameField, targetValueField);
        }
    }

    @Data
    @Builder
    @AllArgsConstructor
    @NoArgsConstructor
    public static class Configuration implements Processor.Configuration {
        private List<String> fields;
        private String targetNameField;
        private String targetValueField;

    }

}